import { ElMessage } from 'element-plus'

/**
 * 颜色转换函数
 * @param str 颜色值字符串
 * @function hexToRgb hex 颜色转 rgb 颜色
 * @function rgbToHex rgb 颜色转 Hex 颜色
 * @function getDarkColor 加深颜色值
 * @function getLightColor 变浅颜色值
 * @returns {any} 返回处理后的字符串
 */
// str 颜色值字符串
const hexToRgb = (str: string): any => {
  let hexs: any = ''
  const reg = /^#?[\dA-Fa-f]{6}$/
  if (!reg.test(str)) {
    ElMessage.warning('输入错误的hex')
    return ''
  }
  str = str.replace('#', '')
  hexs = str.match(/../g)
  for (let index = 0; index < 3; index++) {
    hexs[index] = Number.parseInt(hexs[index], 16)
  }
  return hexs
}
// r 代表红色 | g 代表绿色 | b 代表蓝色
const rgbToHex = (r: any, g: any, b: any): string => {
  const reg = /^\d{1,3}$/
  if (!reg.test(r) || !reg.test(g) || !reg.test(b)) {
    ElMessage.warning('输入错误的rgb颜色值')
    return ''
  }
  const hexs = [r.toString(16), g.toString(16), b.toString(16)]
  for (let index = 0; index < 3; index++) {
    if (hexs[index].length === 1) {
      hexs[index] = `0${hexs[index]}`
    }
  }
  return `#${hexs.join('')}`
}
// color 颜色值字符串 | level 变浅的程度，限0-1之间
const getDarkColor = (color: string, level: number): string => {
  const reg = /^#?[\dA-Fa-f]{6}$/
  if (!reg.test(color)) {
    ElMessage.warning('输入错误的hex颜色值')
    return ''
  }
  const rgb = hexToRgb(color)
  for (let index = 0; index < 3; index++) {
    rgb[index] = Math.floor(rgb[index] * (1 - level))
  }
  return rgbToHex(rgb[0], rgb[1], rgb[2])
}
// color 颜色值字符串 | level 加深的程度，限0-1之间
const getLightColor = (color: string, level: number): string => {
  const reg = /^#?[\dA-Fa-f]{6}$/
  if (!reg.test(color)) {
    ElMessage.warning('输入错误的hex颜色值')
    return ''
  }
  const rgb = hexToRgb(color)
  for (let index = 0; index < 3; index++) {
    rgb[index] = Math.floor((255 - rgb[index]) * level + rgb[index])
  }
  return rgbToHex(rgb[0], rgb[1], rgb[2])
}

export { hexToRgb, rgbToHex, getDarkColor, getLightColor }
